<?php
/**
 * AuthToken
 *
 * @Description 描述
 * @Author look
 * @CreateTime 2022/2/22
 */

namespace app\common\utils;

use app\common\exception\ApiException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

/**
 * 请求认证token
 */
class AuthToken {

    private const ALG = "HS256";

    private const KEY = "hwiyi0HXvJMssE72";

    private const EXP = 3_600 * 24 * 2;

    public function generateToken(array $data): string {
        $data['exp'] = time() + self::EXP;
        return JWT::encode($data, self::KEY, self::ALG);
    }

    public function analysisToken(string $token): array|ApiException {
        try {
            $data = JWT::decode($token, new Key(self::KEY, self::ALG));
        } catch (\Throwable $e) {
            throw new ApiException(...ErrorCode::TOKEN_ERROR);
        }
        return $this->checkData((array)$data);
    }

    private function checkData(array $data): array|ApiException {
        if ($data['exp'] < time()) {
            throw new ApiException(...ErrorCode::TOKEN_OVER);
        }
        if (!isset($data['admin_id']) || !is_integer($data['admin_id'])) {
            throw new ApiException(...ErrorCode::TOKEN_ERROR);
        }
        return $data;
    }

}